<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="旅行社名" prop="agencyName">
        <el-input v-model="queryParams.agencyName" placeholder="请输入旅行社名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="负责人" prop="principalName">
        <el-input v-model="queryParams.principalName" placeholder="请输入负责人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="联系电话" prop="principalPhone">
        <el-input v-model="queryParams.principalPhone" placeholder="请输入联系电话" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="联系邮箱" prop="principalEmail">
        <el-input v-model="queryParams.principalEmail" placeholder="请输入联系邮箱" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable style="width: 205px">
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="项目" prop="projectIds">
        <el-select v-model="queryParams.projectIds" multiple placeholder="请选择项目">
          <el-option v-for="item in projectOptions" :key="item.id" :label="item.name" :value="item.id"
            :disabled="item.status == 1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['lxy:travelagen:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['lxy:travelagen:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain  size="mini" :disabled="multiple" @click="handleStop"
          v-hasPermi="['lxy:travelagen:edit']">一键停用</el-button>
      </el-col>
      <!-- icon="el-icon-edit" -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['lxy:travelagen:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['lxy:travelagen:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="travelagenList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号	" align="center" prop="id" v-if="true" />
      <el-table-column label="旅行社名称" align="center" prop="agencyName" />
      <el-table-column label="用户名" align="center" prop="username" />
      <el-table-column label="负责人" align="center" prop="principalName" />
      <el-table-column label="联系电话" align="center" prop="principalPhone" />
      <!-- <el-table-column label="联系邮箱" align="center" prop="principalEmail" /> -->
      <!-- <el-table-column label="密码" align="center" prop="password" /> -->
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
          <!-- active-text="启用"
          inactive-text="停用" -->
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['lxy:travelagen:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['lxy:travelagen:remove']">删除</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="['lxy:travelagen:resetPwd', 'lxy:travelagen:edit']">
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="handleResetPwd" icon="el-icon-key"
                v-hasPermi="['lxy:travelagen:resetPwd']">重置密码</el-dropdown-item>
              <el-dropdown-item command="handleAuthProject" icon="el-icon-circle-check"
                v-hasPermi="['lxy:travelagen:edit']">分配项目</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改旅行社对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="旅行社名" prop="agencyName">
          <el-input v-model="form.agencyName" placeholder="请输入旅行社名称" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" type="password" maxlength="20" show-password />
        </el-form-item>
        <el-form-item label="负责人" prop="principalName">
          <el-input v-model="form.principalName" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="principalPhone">
          <el-input v-model="form.principalPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="联系邮箱" prop="principalEmail">
          <el-input v-model="form.principalEmail" placeholder="请输入联系邮箱" />
        </el-form-item>
        <el-form-item label="项目">
          <el-select v-model="form.projectIds" multiple placeholder="请选择项目">
            <el-option v-for="item in projectOptions" :key="item.id" :label="item.name" :value="item.id"
              :disabled="item.status == 1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTravelagen, getTravelagen, delTravelagen, addTravelagen, updateTravelagen, stopTravelagen ,changeStatus, resetAgencyPwd } from "@/api/lxy/travelagen";
import { listProject } from "@/api/lxy/project";
export default {
  name: "Travelagen",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 旅行社表格数据
      travelagenList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        username: undefined,
        password: undefined,
        agencyName: undefined,
        principalName: undefined,
        principalPhone: undefined,
        principalEmail: undefined,
        status: undefined,
        projectIds: undefined,
      },
      // 项目选项
      projectOptions: [],
      //状态选项
      statusOptions: [{
        value: 0,
        key: 0,
        label: '正常'

      }, {
        value: 1,
        key: 1,
        label: '停用'
      }],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "编号不能为空", trigger: "blur" }
        ],
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
        ],
        agencyName: [
          { required: true, message: "旅行社名称不能为空", trigger: "blur" }
        ],
        principalName: [
          // { message: "负责人不能为空", trigger: "blur" }
        ],
        principalPhone: [
          // { message: "联系电话不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        principalEmail: [
          // { message: "联系邮箱不能为空", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getProjectList();
  },
  methods: {
    /** 查询旅行社列表 */
    getList() {
      this.loading = true;
      listTravelagen(this.queryParams).then(response => {
        this.travelagenList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /**查询项目列表 */
    getProjectList() {
      this.queryParams.params = {};
      listProject(this.queryParams).then(response => {
        this.projectOptions = response.rows;
      });
    },
    // 旅行社状态修改
    handleStatusChange(row) {
      let text = row.status === 0 ? "启用" : "停用";
      this.$modal.confirm('确认要" ' + text + ' "" ' + row.agencyName + ' "吗？').then(function () {
        return changeStatus(row.id, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === 0 ? 1 : 0;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        username: undefined,
        password: undefined,
        agencyName: undefined,
        principalName: undefined,
        principalPhone: undefined,
        principalEmail: undefined,
        status: "0",
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        projectIds: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthProject":
          this.handleAuthProject(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加旅行社";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getTravelagen(id).then(response => {
        this.loading = false;
        this.form = response.data.agency;
        this.form.status = response.data.agency.status ? "1":"0";
        this.$set(this.form, "projectIds", response.data.projectIds);
        this.open = true;
        this.title = "修改旅行社";
      });
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.agencyName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "密码长度必须介于 5 和 20 之间"
      }).then(({ value }) => {
        resetAgencyPwd(row.id, value).then(response => {
          this.$modal.msgSuccess("修改成功，新密码是：" + value);
        });
      }).catch(() => { });
    },
    /** 分配角色操作 */
    handleAuthProject: function (row) {
      const id = row.id;
      this.$router.push("/lxy/agency-auth/project/" + id);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateTravelagen(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addTravelagen(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除旅行社编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delTravelagen(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 一键停用按钮操作 */
    handleStop(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认停用旅行社编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return stopTravelagen(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("停用成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('lxy/travelagen/export', {
        ...this.queryParams
      }, `travelagen_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

